package com.lx.base.util;

import java.util.*;

/**
 * @author w050000154
 */
public class

TreeHelper {
	/**
	 * 把机构list转成树的节点形式,渲染已选择的节点
	 * @param tree
	 * @param rootLevel
	 * @return
	 */
	public List<Map<String,Object>> renderTree(List<Map<String,Object>> tree,int rootLevel) {
		//机构根节点
		List<Map<String,Object>> root = new ArrayList<Map<String,Object>>();
		//查询角色已选择的机构id
		//List<String> checkedOrgId = adminAuthRoleOrgMapper.findOrgIdByRoleIdAndAuthSystem(roleId, authSystem);
		List<Map<String,Object>> tempList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> checkList=new ArrayList<Map<String,Object>>();
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("type", "0");
		map.put("checked", "0");
		checkList.add(map);
		for(Map<String,Object> node:tree) {
			String orgId = (String) node.get("id");

			//前端多选需要
			/*node.put("checkArr", map);*/
			node.put("checked", false);
			if (rootLevel == Integer.parseInt(node.get("orglevelcodes") == null ? "-2" : String.valueOf(node.get("orglevelcodes")))) {
				node.put("spread", true);
				root.add(node);
			}
			tempList.add(node);
		}
		//查找根节点的子节点
		List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
		Collections.sort(tempList, this.getComparator());
		for(Map<String,Object> r:root) {
			r.put("children", findChildren((String) r.get("id"),tempList));
			resultList.add(r);
		}
		return resultList;
	}

	/**
	 * 查找根节点下的子节点
	 * @param pid
	 * @param resultMap
	 * @return
	 */
	private List<Map<String,Object>> findChildren(String pid ,List<Map<String,Object>> resultMap){
		List<Map<String,Object>> childrenList = new ArrayList<Map<String,Object>>();
		if(resultMap != null && resultMap.size() > 0) {
			for(Map<String,Object> node:resultMap) {
				if(pid.equals(node.get("pid"))) {
					node.put("children", findChildren((String) node.get("id"),resultMap));
					childrenList.add(node);
				}
			}
		}
		return childrenList;

	}

	private Comparator<Map<String,Object>> getComparator() {
		Comparator<Map<String,Object>> com = new Comparator<Map<String,Object>>() {
			@Override
			public int compare(Map<String,Object> o1, Map<String,Object> o2) {
				if(((String)o1.get("id")) == null && ((String)o2.get("id")) == null) {
					return 1;
				}else if(((String)o1.get("id")) != null && ((String)o2.get("id")) == null) {
					return 1;
				}else if(((String)o1.get("id")) == null && ((String)o2.get("id")) != null) {
					return -1;
				}else {
					if(((String)o1.get("id")).length() > ((String)o2.get("id")).length()) {
						return 1;
					}else if(((String)o1.get("id")).length() < ((String)o2.get("id")).length()) {
						return -1;
					}else {
						return ((String)o1.get("id")).compareTo(((String)o2.get("id")));
					}
				}
			}
		};
		return com;
	}
}
